<template>
  <div class="course-management-container">
    <div class="header">
      <h1>课程管理</h1>
      <p>管理您的课程内容和学习资源</p>
    </div>

    <!-- 功能导航 -->
    <div class="navigation-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="我的课程" name="my-courses">
          <el-button
            v-if="hasRole('LECTURER') || hasRole('ADMIN')"
            type="primary"
            @click="createNewCourse"
          >
            创建课程
          </el-button>
        </el-tab-pane>
        <el-tab-pane label="课程分类管理" name="categories" v-if="hasRole('ADMIN')">
        </el-tab-pane>
        <el-tab-pane label="视频管理" name="videos" v-if="hasRole('LECTURER') || hasRole('ADMIN')">
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 我的课程列表 -->
    <div v-if="activeTab === 'my-courses'" class="courses-section">
      <el-table
        :data="courses"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="title" label="课程标题" width="200" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="status" label="状态" width="200">
          <template #default="scope">
            <div class="status-cell">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
              <div v-if="scope.row.publishTime" style="font-size: 11px; color: #67c23a;">
                {{ formatDate(scope.row.publishTime) }}
              </div>
              <div v-else style="font-size: 11px; color: #909399;">
                未发布
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="280" />
        <el-table-column label="操作" width="450">
          <template #default="scope">
            <el-button size="small" @click="editCourse(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="primary"
              @click="viewCourseDetails(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'"
              @click="scope.row.status === 'ACTIVE' ? unpublishCourse(scope.row) : publishCourse(scope.row)"
              v-if="hasRole('LECTURER') || hasRole('ADMIN')"
            >
              {{ scope.row.status === 'ACTIVE' ? '取消发布' : '发布' }}
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="deleteCourse(scope.row)"
              v-if="hasRole('LECTURER') || hasRole('ADMIN')"
            >
              删除
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="uploadVideo(scope.row)"
              v-if="hasRole('LECTURER')"
            >
              上传视频
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="manageEnrollments(scope.row)"
              v-if="hasRole('LECTURER') || hasRole('ADMIN')"
            >
              人员审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="totalCourses"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 课程分类管理 -->
    <div v-else-if="activeTab === 'categories'" class="categories-section">
      <el-card class="category-card">
        <template #header>
          <div class="card-header">
            <h3>课程分类管理</h3>
          </div>
        </template>
        <div class="category-form">
          <el-form :model="categoryForm" label-width="100px">
            <el-form-item label="分类名称">
              <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
            </el-form-item>
            <el-form-item label="分类描述">
              <el-input v-model="categoryForm.description" type="textarea" placeholder="请输入分类描述" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveCategory">保存分类</el-button>
              <el-button @click="resetCategoryForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="category-list">
          <h4>现有分类</h4>
          <el-table :data="categories" border style="width: 100%">
            <el-table-column prop="name" label="分类名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editCategory(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCategory(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 视频管理 -->
    <div v-else-if="activeTab === 'videos'" class="videos-section">
      <el-card class="video-card">
        <template #header>
          <div class="card-header">
            <h3>视频管理</h3>
            <el-button type="primary" @click="showUploadDialog = true">上传视频</el-button>
          </div>
        </template>

        <!-- 筛选器 -->
        <div class="filter-section" style="margin-bottom: 20px;">
          <el-select
            v-model="videoFilterStatus"
            placeholder="请选择审核状态"
            @change="filterVideos"
            clearable
            style="width: 200px;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="待审核" value="PENDING"></el-option>
            <el-option label="已批准" value="APPROVED"></el-option>
            <el-option label="已拒绝" value="REJECTED"></el-option>
          </el-select>
          <el-button @click="resetVideoFilter" style="margin-left: 10px;">重置筛选</el-button>
        </div>

        <el-table :data="filteredVideos" border style="width: 100%" v-loading="loading" class="video-table">
          <el-table-column prop="title" label="视频标题" width="250">
            <template #default="scope">
              <div class="video-title-cell">
                <div class="video-title">{{ scope.row.title }}</div>
                <div class="video-description">{{ scope.row.description }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="时长(分钟)" width="120">
            <template #default="scope">
              {{ formatDuration(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="上传时间" width="180">
            <template #default="scope">
              {{ scope.row.createdTime ? formatDate(scope.row.createdTime) : '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button size="small" @click="viewVideoDetails(scope.row)">查看</el-button>
              <el-button
                size="small"
                type="primary"
                @click="reviewVideo(scope.row)"
                v-if="hasRole('ADMIN') && scope.row.status === 'PENDING'"
              >
                审核
              </el-button>
              <el-button size="small" type="danger" @click="deleteVideo(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container" v-if="filteredVideos.length > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="filteredVideos.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 视频播放器对话框 -->
    <el-dialog
      v-model="showVideoPlayer"
      width="800px"
      :destroy-on-close="true"
      @close="closeVideoPlayer"
    >
      <VideoPlayer
        v-if="selectedVideo"
        :video="selectedVideo"
        :api-base-url="apiBaseUrl"
        :on-close="closeVideoPlayer"
      />
    </el-dialog>

    <!-- 创建课程对话框 -->
    <el-dialog
      v-model="showCreateCourseDialog"
      title="创建课程"
      width="500px"
    >
      <el-form :model="createCourseForm" label-width="100px">
        <el-form-item label="课程标题">
          <el-input v-model="createCourseForm.title" placeholder="请输入课程标题" />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select v-model="createCourseForm.category" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.name"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input
            v-model="createCourseForm.description"
            type="textarea"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="avatar-uploader"
            :action="`${apiBaseUrl}/api/files/upload-course-cover`"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeUpload"
            :headers="uploadHeaders"
          >
            <img
              v-if="createCourseForm.coverImage"
              :src="createCourseForm.coverImage"
              class="avatar"
              style="max-width: 178px; max-height: 178px; object-fit: cover;"
              @error="handleCoverImageError"
              :key="createCourseForm.coverImage"
            />
            <el-avatar v-else :size="100"><el-icon><Collection /></el-icon></el-avatar>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateCourseDialog = false">取消</el-button>
          <el-button type="primary" @click="createCourse">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 视频上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传视频"
      width="500px"
    >
      <el-form :model="uploadVideoForm" label-width="100px">
        <el-form-item label="选择课程">
          <el-select v-model="uploadVideoForm.courseId" placeholder="请选择课程">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="视频文件">
          <input type="file" ref="videoFileInput" accept="video/*" @change="handleVideoFileSelect" style="display: none;" />
          <el-button type="primary" @click="$refs.videoFileInput.click()">选择视频文件</el-button>
          <span v-if="uploadVideoForm.videoFile" style="margin-left: 10px;">{{ uploadVideoForm.videoFile.name }}</span>
        </el-form-item>
        <el-form-item label="视频标题">
          <el-input v-model="uploadVideoForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频描述">
          <el-input
            v-model="uploadVideoForm.description"
            type="textarea"
            placeholder="请输入视频描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
          <el-button type="primary" @click="uploadVideoFile">上传</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 人员审批对话框 -->
    <el-dialog
      v-model="showEnrollmentDialog"
      :title="`课程人员审批 - ${selectedCourse?.title}`"
      width="800px"
    >
      <el-table :data="courseEnrollments" border style="width: 100%">
        <el-table-column prop="user.name" label="学员姓名" width="150" />
        <el-table-column prop="user.username" label="用户名" width="150" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getEnrollmentStatusTagType(scope.row.status)">
              {{ getEnrollmentStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="approveEnrollment(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              通过
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="rejectEnrollment(scope.row)"
              v-if="scope.row.status === 'PENDING' || scope.row.status === 'APPROVED'"
            >
              {{ scope.row.status === 'PENDING' ? '拒绝' : '撤销通过' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEnrollmentDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Collection,
  Clock,
  Plus,
  Upload
} from '@element-plus/icons-vue'
import request from '../../utils/request'
import { hasRole } from '../../utils/auth'
import VideoPlayer from '../../components/VideoPlayer.vue'

// 路由
const router = useRouter()

// 数据
const activeTab = ref('my-courses')
const courses = ref([])
const categories = ref([])
const videos = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCourses = ref(0)
const currentEditCourseId = ref(null)
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { Authorization: `Bearer ${token}` } : {}
})

// 人员审批相关数据
const showEnrollmentDialog = ref(false)
const courseEnrollments = ref([])
const selectedCourse = ref(null)

// 视频播放器相关数据
const showVideoPlayer = ref(false)
const selectedVideo = ref(null)

// 视频筛选相关数据
const videoFilterStatus = ref('')
const filteredVideos = ref([])

// 表单数据
const showCreateCourseDialog = ref(false)
const showUploadDialog = ref(false)
const createCourseForm = ref({
  title: '',
  category: '',
  description: '',
  coverImage: ''
})

const uploadVideoForm = ref({
  courseId: '',
  videoFile: null,
  title: '',
  description: ''
})

const categoryForm = ref({
  name: '',
  description: ''
})

// 生命周期
onMounted(() => {
  loadCourses()
  loadCategories()
})

// 方法
const handleTabChange = (tab) => {
  if (tab === 'my-courses') {
    loadCourses()
  } else if (tab === 'categories') {
    loadCategories()
  } else if (tab === 'videos') {
    loadVideos()
  }
}

const loadCourses = async () => {
  loading.value = true
  try {
    // Load courses from the same endpoint for all users
    const response = await request.get('/api/study/courses', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value
      }
    })

    let filteredCourses = response.data.content;

    // For LECTURER users, filter to show only courses they created
    if (!hasRole('ADMIN')) {
      // Get current user info from localStorage to filter courses
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          const currentUserId = userInfo.id;

          if (currentUserId) {
            // Filter courses to show only those created by current user
            filteredCourses = response.data.content.filter(course => {
              // Support different possible creator field names
              return course.creatorId === currentUserId ||
                     (course.creator && course.creator.id === currentUserId) ||
                     (course.creatorId && course.creatorId === currentUserId);
            });

          } else {
            // If no user ID, show empty list
            filteredCourses = [];
          }
        } catch (parseError) {

          filteredCourses = response.data.content;
        }
      } else {
        // If no user info, show empty list for LECTURER users
        filteredCourses = [];
      }
    }

    courses.value = filteredCourses;
    totalCourses.value = filteredCourses.length;
  } catch (error) {
    console.error('加载课程失败:', error)
    ElMessage.error('加载课程失败')
    courses.value = [];
    totalCourses.value = 0;
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    // Try to load categories - if user doesn't have permission, silently handle it
    const response = await request.get('/api/study/courses/categories')
    categories.value = response.data
  } catch (error) {
    // If access is denied or any other error, just clear categories
    // This prevents the app from crashing and shows that categories are not available
    categories.value = []
    // Log to console for debugging but don't show user-facing error
    if (error.response?.status !== 403) {
      console.error('加载分类失败:', error)
    }
  }
}

const loadVideos = async () => {
  try {
    loading.value = true;
    const token = localStorage.getItem('token');
    if (!token) {
      videos.value = [];
      filteredVideos.value = [];
      loading.value = false;
      return;
    }

    // For admin users, show all videos
    // For LECTURER users, show videos they uploaded
    let response;
    if (hasRole('ADMIN')) {
      // Use the endpoint to get all videos for admin users
      response = await request.get('/api/study/videos/all', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
    } else {
      // For LECTURER users, load videos they uploaded
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          const currentUserId = userInfo.id;

          if (currentUserId) {
            // For LECTURER users, we'll fetch videos based on the creator ID
            response = await request.get(`/api/study/videos/created-by/${currentUserId}`, {
              headers: {
                'Authorization': `Bearer ${token}`
              }
            });
          } else {
            videos.value = [];
            filteredVideos.value = [];
            loading.value = false;
            return;
          }
        } catch (parseError) {
          console.error('Failed to parse user info:', parseError);
          // Show a more user-friendly error message
          ElMessage.error('无法获取用户信息，请重新登录');
          videos.value = [];
          filteredVideos.value = [];
          loading.value = false;
          return;
        }
      } else {
        // No user info found in localStorage
        ElMessage.error('未找到用户信息，请重新登录');
        videos.value = [];
        filteredVideos.value = [];
        loading.value = false;
        return;
      }
    }

    // Check if response has the expected structure
    if (response && response.data && response.data.success) {
      videos.value = response.data.videos || [];
      // Initialize filtered videos with all videos
      filteredVideos.value = videos.value;
    } else {
      videos.value = [];
      filteredVideos.value = [];
      console.warn('视频数据格式不正确:', response);
    }
  } catch (error) {
    // Handle the 403 Forbidden error specifically
    if (error.response && error.response.status === 403) {
      console.error('权限不足，无法加载视频:', error);
      ElMessage.error('权限不足，无法加载视频信息');
    } else if (error.response && error.response.status === 401) {
      console.error('未授权访问，需要登录:', error);
      ElMessage.error('会话已过期，请重新登录');
    } else {
      console.error('加载视频失败:', error);
      ElMessage.error('加载视频失败: ' + (error.response?.data?.message || error.message));
    }
    videos.value = [];
    filteredVideos.value = [];
  } finally {
    loading.value = false;
  }
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'ACTIVE': return 'success'
    case 'INACTIVE': return 'info'
    case 'PENDING': return 'warning'
    case 'REJECTED': return 'danger'
    default: return 'info'
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDuration = (fileSize) => {
  if (!fileSize || fileSize <= 0) return '未知'
  // This is a rough estimation - in a real application, you would get this from video metadata
  // Assuming average bitrate of 1 MB per minute for estimation
  const minutes = Math.round(fileSize / (1024 * 1024) / 1)
  return minutes > 0 ? minutes : '未知'
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'ACTIVE': return '已发布'
    case 'INACTIVE': return '未发布'
    case 'PENDING': return '待审核'
    case 'REJECTED': return '已拒绝'
    default: return status
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadCourses()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadCourses()
}

/**
 * 编辑课程
 */
const editCourse = (course) => {
  // 这里应该填充表单并显示编辑对话框
  createCourseForm.value = {
    title: course.title,
    category: course.category,
    description: course.description,
    coverImage: course.coverImage ? (course.coverImage.startsWith('http') ? course.coverImage : `${apiBaseUrl}${course.coverImage}`) : ''
  }
  showCreateCourseDialog.value = true
  // 保存原始课程ID，用于更新操作
  currentEditCourseId.value = course.id
}

/**
 * 创建新课程
 */
const createNewCourse = () => {
  // 清空表单数据，创建全新课程
  createCourseForm.value = {
    title: '',
    category: '',
    description: '',
    coverImage: ''
  }
  showCreateCourseDialog.value = true
  currentEditCourseId.value = null
}

/**
 * 查看课程详情
 */
const viewCourseDetails = (course) => {
  router.push(`/study/courses/${course.id}`)
}

/**
 * 上传视频
 */
const publishCourse = async (course) => {
  try {
    await request.put(`/api/study/courses/${course.id}/publish`)
    ElMessage.success('课程发布成功')
    loadCourses()
  } catch (error) {
    console.error('发布课程失败:', error)
    ElMessage.error('发布课程失败')
  }
}

const unpublishCourse = async (course) => {
  try {
    await request.put(`/api/study/courses/${course.id}/unpublish`)
    ElMessage.success('课程取消发布成功')
    loadCourses()
  } catch (error) {
    console.error('取消发布课程失败:', error)
    ElMessage.error('取消发布课程失败')
  }
}

const deleteCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个课程吗？此操作不可撤销',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request.delete(`/api/study/courses/${course.id}`)
    ElMessage.success('课程删除成功')
    loadCourses()
  } catch (error) {
    console.error('删除课程失败:', error)
    ElMessage.error('删除课程失败')
  }
}

const uploadVideo = (course) => {
  uploadVideoForm.value.courseId = course.id
  showUploadDialog.value = true
}

/**
 * 管理课程报名人员
 */
const manageEnrollments = async (course) => {
  try {
    selectedCourse.value = course
    loading.value = true
    
    // 获取课程的报名信息
    const response = await request.get(`/api/study/courses/${course.id}/enrollments`)
    if (response.data.success) {
      courseEnrollments.value = response.data.enrollments || []
    } else {
      courseEnrollments.value = []
    }
    
    showEnrollmentDialog.value = true
  } catch (error) {
    console.error('获取课程报名信息失败:', error)
    ElMessage.error('获取课程报名信息失败')
    courseEnrollments.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 通过报名申请
 */
const approveEnrollment = async (enrollment) => {
  try {
    const response = await request.put(`/api/study/courses/${selectedCourse.value.id}/enrollments/${enrollment.id}/approve`)
    if (response.data.success) {
      ElMessage.success('报名申请已通过')
      // 更新本地数据
      const index = courseEnrollments.value.findIndex(item => item.id === enrollment.id)
      if (index !== -1) {
        courseEnrollments.value[index].status = 'APPROVED'
      }
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('通过报名申请失败:', error)
    ElMessage.error('通过报名申请失败')
  }
}

/**
 * 拒绝报名申请
 */
const rejectEnrollment = async (enrollment) => {
  try {
    let response;
    if (enrollment.status === 'PENDING') {
      // 拒绝待审批的申请
      response = await request.put(`/api/study/courses/${selectedCourse.value.id}/enrollments/${enrollment.id}/reject`)
    } else if (enrollment.status === 'APPROVED') {
      // 撤销已通过的审批
      response = await request.put(`/api/study/courses/${selectedCourse.value.id}/enrollments/${enrollment.id}/revoke`)
    }
    
    if (response.data.success) {
      ElMessage.success(enrollment.status === 'PENDING' ? '报名申请已拒绝' : '报名审批已撤销')
      // 更新本地数据
      const index = courseEnrollments.value.findIndex(item => item.id === enrollment.id)
      if (index !== -1) {
        courseEnrollments.value[index].status = enrollment.status === 'PENDING' ? 'REJECTED' : 'PENDING'
      }
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

/**
 * 获取报名状态标签类型
 */
const getEnrollmentStatusTagType = (status) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'APPROVED': return 'success'
    case 'REJECTED': return 'danger'
    default: return 'info'
  }
}

/**
 * 获取报名状态文本
 */
const getEnrollmentStatusText = (status) => {
  switch (status) {
    case 'PENDING': return '待审批'
    case 'APPROVED': return '已通过'
    case 'REJECTED': return '已拒绝'
    default: return status
  }
}

/**
 * 查看用户详情
 */
const viewUserProfile = (userId) => {
  // 这里可以跳转到用户详情页面或显示用户详情对话框
  ElMessage.info('查看用户详情功能待实现')
}

const closeVideoPlayer = () => {
  // 先重置选中的视频，再关闭对话框
  selectedVideo.value = null
  nextTick(() => {
    // 添加一个小延迟确保DOM更新完成
    setTimeout(() => {
      showVideoPlayer.value = false
    }, 100)
  })
}

// 视频筛选方法
const filterVideos = () => {
  if (!videoFilterStatus.value) {
    // 如果没有筛选条件，显示所有视频
    filteredVideos.value = videos.value
  } else {
    // 根据状态筛选视频
    filteredVideos.value = videos.value.filter(video => video.status === videoFilterStatus.value)
  }
  // 重新初始化分页
  currentPage.value = 1
}

const resetVideoFilter = () => {
  videoFilterStatus.value = ''
  filteredVideos.value = videos.value
}

const openVideoPlayer = (video) => {
  selectedVideo.value = video
  showVideoPlayer.value = true
}

const createCourse = async () => {
  try {
    if (currentEditCourseId.value) {
      // 更新课程
      await request.put(`/api/study/courses/${currentEditCourseId.value}`, createCourseForm.value)
      ElMessage.success('更新课程成功')
    } else {
      // 创建课程
      await request.post('/api/study/courses', createCourseForm.value)
      ElMessage.success('创建课程成功')
    }
    showCreateCourseDialog.value = false
    createCourseForm.value = {
      title: '',
      category: '',
      description: '',
      coverImage: ''
    }
    currentEditCourseId.value = null
    loadCourses()
  } catch (error) {
    console.error('操作课程失败:', error)
    ElMessage.error(currentEditCourseId.value ? '更新课程失败' : '创建课程失败')
  }
}

const uploadVideoFile = async () => {
  try {
    if (!uploadVideoForm.value.courseId || !uploadVideoForm.value.videoFile || !uploadVideoForm.value.title) {
      ElMessage.error('请完整填写视频信息')
      return
    }

    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', uploadVideoForm.value.videoFile)
    formData.append('title', uploadVideoForm.value.title)
    formData.append('description', uploadVideoForm.value.description)
    formData.append('courseId', uploadVideoForm.value.courseId)

    // 使用request库发送上传请求 to the new video upload endpoint
    const response = await request.post('/api/study/videos', formData)

    if (response.data.success) {
      ElMessage.success('视频上传成功')
      showUploadDialog.value = false
      uploadVideoForm.value = {
        courseId: '',
        videoFile: null,
        title: '',
        description: ''
      }
      loadVideos()
    } else {
      ElMessage.error(response.data.message || '视频上传失败')
    }
  } catch (error) {
    console.error('视频上传失败:', error)
    ElMessage.error(error.response?.data?.message || '视频上传失败')
  }
}

const saveCategory = async () => {
  try {
    await request.post('/api/study/categories', categoryForm.value)
    ElMessage.success('保存分类成功')
    resetCategoryForm()
    loadCategories()
  } catch (error) {
    console.error('保存分类失败:', error)
    ElMessage.error('保存分类失败')
  }
}

const editCategory = (category) => {
  categoryForm.value = { ...category }
}

const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个分类吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request.delete(`/api/study/categories/${category.id}`)
    ElMessage.success('删除分类成功')
    loadCategories()
  } catch (error) {
    console.error('删除分类失败:', error)
    ElMessage.error('删除分类失败')
  }
}

const resetCategoryForm = () => {
  categoryForm.value = {
    name: '',
    description: ''
  }
}

const handleCoverSuccess = (response, file) => {
  if (response.success && response.url) {
    // 确保使用完整的API URL
    if (response.url.startsWith('/')) {
      createCourseForm.value.coverImage = `${apiBaseUrl}${response.url}`;
    } else {
      createCourseForm.value.coverImage = response.url;
    }
  }
}

const handleCoverImageError = (error) => {
  console.error('图片加载失败:', error);
  // 可以在这里添加默认图片或其他处理逻辑
}

// Removed handleVideoSuccess since we're handling uploads manually

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJPG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  return true
}

const beforeVideoUpload = (file) => {
  const isMP4 = file.type === 'video/mp4'
  const isAVI = file.type === 'video/avi'
  const isMOV = file.type === 'video/quicktime'
  const isWMV = file.type === 'video/x-ms-wmv'

  if (!isMP4 && !isAVI && !isMOV && !isWMV) {
    ElMessage.error('只能上传 MP4、AVI、MOV 或 WMV 格式的视频!')
    return false
  }
  return true
}

const handleVideoFileSelect = (event) => {
  const file = event.target.files[0]
  if (file && beforeVideoUpload(file)) {
    uploadVideoForm.value.videoFile = file
  }
}

const viewVideo = (video) => {
  playVideo(video)
}

const manageAccess = (video) => {
  reviewVideo(video)
}

const deleteVideo = async (video) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个视频吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request.delete(`/api/study/videos/${video.id}`)
    ElMessage.success('删除视频成功')
    loadVideos()
  } catch (error) {
    console.error('删除视频失败:', error)
    ElMessage.error('删除视频失败')
  }
}

// 新增功能：查看视频详情
const viewVideoDetails = (video) => {
  openVideoPlayer(video)
}

// 新增功能：播放视频
const playVideo = (video) => {
  openVideoPlayer(video)
}

// 新增功能：审核视频（仅管理员可见）
const reviewVideo = async (video) => {
  if (!hasRole('ADMIN')) {
    ElMessage.error('您没有权限执行此操作')
    return
  }

  try {
    // 显示审核对话框
    const action = await ElMessageBox.confirm(
      `待审核视频： "${video.title}" 是否允许上架：`,
      '审核视频',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '允许',
        cancelButtonText: '拒绝',
        type: 'warning'
      }
    ).then(() => 'approve').catch((action) => action)

    if (action === 'approve') {
      // 通过审核
      const response = await request.put(`/api/study/videos/${video.id}/approve`)
      if (response.data.success) {
        ElMessage.success('视频审核通过')
        loadVideos()
      } else {
        ElMessage.error(response.data.message || '审核失败')
      }
    } else if (action === 'cancel') {
      // 拒绝审核
      const response = await request.put(`/api/study/videos/${video.id}/reject`)
      if (response.data.success) {
        ElMessage.success('视频审核已拒绝')
        loadVideos()
      } else {
        ElMessage.error(response.data.message || '拒绝失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      console.error('审核视频失败:', error)
      ElMessage.error('审核操作失败')
    }
  }
}
</script>

<style scoped>
.course-management-container {
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.navigation-tabs {
  margin-bottom: 30px;
}

.courses-section, .categories-section, .videos-section {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-form {
  margin-bottom: 20px;
}

.category-list {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 视频表格样式优化 */
.video-table .el-table__row:hover {
  background-color: #f5f7fa;
}

.video-title-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.video-title {
  font-weight: 500;
  color: #303133;
}

.video-description {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.filter-section {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/* 优化状态显示样式 */
.status-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
</style>
